import request from './request.js'
import config from '../config/api.config.js'

let PlatformType;

// #ifdef MP-QQ
PlatformType = 1;
// #endif
// #ifdef MP-WEIXIN
PlatformType = 2;
// #endif
// #ifdef MP-TOUTIAO
PlatformType = 3;
// #endif
			

function loginAction(callback,parentOpenid) {
	console.log(callback)
	uni.login({
		async success(r) {
			const r2 = await request({
				url: `${config.API}api/getOpenid`,
				data: {
					code: r.code,
					platform: PlatformType,
					parentOpenid:parentOpenid
				}
			});
			if (r2.error_code === 0) {
				uni.setStorage({
					key: 'openid',
					data: r2.data.openid
				});
				callback && callback(r2.data.openid);
			} else {
				uni.showToast({
					title: '获取openid失败'
				});
			}
		}
	});
};



function checkSession(callback,parentOpenid){
	uni.checkSession({
		success(r) {
			uni.getStorage({
				key: 'openid',
				success(r) {
					if (!r.data) {
						loginAction(callback,parentOpenid);
					} else {
						callback && callback(r.data);
					}
				},
				fail(err) {
					loginAction(callback,parentOpenid);
				}
			})
		},
		fail(err) {
			loginAction(callback,parentOpenid);
		}
	});
};



export default{
	checkSession,
	PlatformType
}